package xworker.gluon.attach.audiorecoding;

import com.gluonhq.attach.audiorecording.AudioRecordingService;
import javafx.collections.ListChangeListener;
import org.xmeta.ActionContext;
import org.xmeta.Thing;

public class AudioRecodingActions {
    public static AudioRecordingService startRecording(ActionContext actionContext){
        Thing self = actionContext.getObject("self");

        Float sampleRate = self.doAction("getSampleRate", actionContext);
        Integer sampleSizeInBits = self.doAction("getSampleSizeInBits", actionContext);
        Integer channels = self.doAction("getChannels", actionContext);
        Integer chunkRecordTime = self.doAction("getChunkRecordTime", actionContext);
        Boolean clearAudioFolder = self.doAction("isClearAudioFolder", actionContext);
        String audioFolderName = self.doAction("getAudioFolderName​", actionContext);

        AudioRecordingService service = AudioRecordingService.create().orElse(null);
        if(service != null){
            if(audioFolderName != null && !audioFolderName.isEmpty()){
                service.setAudioFolderName(audioFolderName);
            }

            if(clearAudioFolder){
                service.clearAudioFolder();
            }

            service.getAudioChunkFiles().addListener((ListChangeListener<String>) c -> {
                self.doAction("onChanged", actionContext, "c", c, "service", service);
            });
            service.startRecording(sampleRate, sampleSizeInBits, channels, chunkRecordTime);
        }

        return service;
    }

    public static void stopRecording(ActionContext actionContext){
        Thing self = actionContext.getObject("self");

        AudioRecordingService service = self.doAction("getAudioRecordingService", actionContext);
        if(service != null){
            service.stopRecording();
        }
    }

}
